<?php

namespace app\admin\model;

use app\common\model\UserRecyclerInfo;
use think\Cache;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;


class Region extends Model
{
    // 表名
    protected $name = 'region';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];

    public function getStatusList()
    {
        return ['1' => __('Status 1'), '0' => __('Status 0')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getLocationAttr($value, $data)
    {
        $location = Db::name('RegionLocation')->field('lat,lng')->where(['region_id' => $data['id']])->select();
        return $location;
    }

    public function admin()
    {
        return $this->belongsTo('Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 片区坐标中心到redis
     * Name: aaasa
     * User: 陈
     * Date: 2021/12/16 22:49
     */
    public static function regionToRedis()
    {
        $regions    = self::where(['status' => 1])->select();
        $redis      = Cache::store('redis')->handler();
        foreach ($regions as $v) {
            if (method_exists($redis, 'geoadd')) {
                $locations  = Db::name('RegionLocation')->field('lat,lng')->where(['region_id' => $v['id']])->select();
                $site       = get_center_from_degrees($locations);
                $redis->geoadd('geo:region', $site['lng'], $site['lat'], $v['id']);
            }
        }

        Cache::tag('geo')->set('geo:region', true, 60 * 60 * 24 * 7);
    }

    /**
     * Name: 根据经纬度获取所在区域
     * User: 陈
     * Date: 2021/12/16 23:10
     */
    public static function siteToRegion($site = [])
    {
        if (Cache::tag('geo')->get('geo:region') !== true) {
            self::regionToRedis();
        }
        $redis = Cache::store('redis')->handler();
        $georadiuslist = [];
        if (method_exists($redis, 'georadius')) {
            $georadiuslist = $redis->georadius('geo:region', $site['lng'], $site['lat'], 50, 'km', ['WITHDIST', 'COUNT' => 10, 'ASC']);
        }

        $id = 0;
        if ($georadiuslist) {
            foreach ($georadiuslist as $v) {
                if (vaildate_point($site, Db::name('RegionLocation')->field('lat,lng')->where(['region_id' => $v[0]])->select())) {
                    $id = $v[0];
                    break;
                }
            }
        }

        return $id;
    }
}
